//
// Created by tongj on 2023/10/7.
//

#ifndef TBS_CPP_MESSAGEQUEUE_H
#define TBS_CPP_MESSAGEQUEUE_H

#include <base/base.hpp>
#include <MessageQueue/Message.h>
#include <queue>
#include <condition_variable>
#include <atomic>
#include <list>

namespace MessageQueue {

class MsgQueue {
public:
  /**
   * 执行消息队列
   */
  void execute();

  /**
   * 队列是否在运行
   * @return
   */
  bool is_execute() CONST;

  /**
   * 发送延时消息
   * @param item
   */
  void send(MessageQueue::DelayMessage &&item);

  /**
   * 消息队列是否为空
   * @return
   */
  bool isEmpty() CONST;

  /**
   * 取消loop
   */

  void cancel();

  size_t messageCount() CONST;

private:
  struct DelayMessageCompartor {
	bool operator()(CONST DelayMessage &a, CONST DelayMessage &b) {
	  return DelayMessage::compare(a, b);
	}
  };

  std::priority_queue<MessageQueue::DelayMessage, std::deque<DelayMessage>, DelayMessageCompartor> _q;

  std::mutex _r_mutex, _w_mutex;
  std::condition_variable _cv;
  std::atomic_bool _cancel_flag{false}, _run_flag{false};
};

}

#endif // TBS_CPP_MESSAGEQUEUE_H
